package panel.common;

import javax.swing.*;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class TextField extends Base.TextField {
    public JTextField textField = new JTextField();
    public TextField(String text) {
        super.init(text);
        // 文本框
        textField.setText(name);
        textField.setBorder(null);
        textField.setBounds(64, 0, getWidth() - 64 - 64 - 10, 64);
        textField.setForeground(Color.gray);
        textField.setFont(font);
        textField.setHorizontalAlignment(SwingConstants.CENTER);
        add(textField);

        clearButton.addActionListener(e -> {
            textField.setText("");
            data="";
            System.out.print("clear\n");
        });
        // 焦点监听
        textField.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
//                System.out.print("正在编辑:" + name + "\n");
                clearButton.setVisible(true);
                textField.setForeground(Color.black);
                textField.setText(data);
            }

            @Override
            public void focusLost(FocusEvent e) {
//                System.out.print("退出编辑:" + name + "\n");
                clearButton.setVisible(false);
                data = textField.getText();
                if (data.isEmpty()) {
                    textField.setText(name);
                    textField.setForeground(Color.gray);
                } else {
                    textField.setForeground(Color.black);
                }
            }
        });
    }

    public void setSize(int width, int height) {
        super.setSize(width, height);
        textField.setBounds(64+5, 0, getWidth() - 64 - 64 - 10, 64);
    }

    public void setBounds(int x, int y, int width, int height) {
        super.setBounds(x, y, width, height);
        textField.setBounds(64+5, 0, getWidth() - 64 - 64 - 10, 64);
    }

    // 设置长度文本框最大长度
    public void setMaxLength(int maxLength) {
        textField.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {
                if (textField.getText().length() >= maxLength) {
                    e.consume();
                }
            }

            @Override
            public void keyPressed(KeyEvent e) {
                //do nothing
            }

            @Override
            public void keyReleased(KeyEvent e) {
                //do nothing
            }
        });
    }

    public String getText() {
        return data;
    }

    public void clear() {
        textField.setText("");
        data = "";
    }
}
